package com.fruit.service.weather.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fruit.pojo.goods.Base;
import com.fruit.pojo.weather.WeatherParams;
import com.fruit.service.goods.BaseManager;
import com.fruit.service.weather.WeatherManager;
import com.fruit.util.Exceptions;
import com.fruit.util.WeatherUtil;

/**
 * 天气相关服务
 * @author Administrator
 * @version 2017.11.30 17:40
 */
@Service
public class WeatherService implements WeatherManager {
	private Logger logger = LoggerFactory.getLogger(WeatherService.class);
	@Autowired
	private BaseManager baseManager;
	
	@Override
	public void updateAllBaseWeather() {
		logger.info("【基地天气更新】--【开始】----");
		try {
			List<Base> baseList = baseManager.getBaseInfo();
			for (Base ba : baseList) {
				//1、获取天气
				String res = getWeather(ba.getCity());
				if (StringUtils.isEmpty(res)) {
					continue; //跳过继续执行
				}
				logger.info("【基地天气更新】--【获取天气结果】----" + res);
				//获取天气
				WeatherParams wp = parseWeather(res);
				if (wp != null) {
					logger.info("【基地天气更新】--【解析结果】----[Weather=" + wp.getWeather() + ";Humidity=" + wp.getHumidity() + ";Temperature=" + wp.getTemperature() + "]");
					ba.setWeather(wp.getWeather());
					ba.setHumidity(wp.getHumidity());
					ba.setTemperature(wp.getTemperature());
					ba.setWeatherType(wp.getCode());
					try {
						int i = baseManager.updateBase(ba);
						if (i <= 0) {
							logger.error("【基地天气更新】--【更新失败】----[id=" + ba.getId() + ";name=" + ba.getName() + "]");
						} else {
							logger.info("【基地天气更新】--【更新成功】----[id=" + ba.getId() + ";name=" + ba.getName() + "]");
						}
					} catch (Exception e) {
						logger.error("【基地天气更新】--【更新异常】----[id=" + ba.getId() + ";name=" + ba.getName() + "]");
						continue; //跳过继续执行
					}
				} else {
					logger.info("【基地天气更新】--【解析结果异常】----");
					continue; //跳过继续执行
				}
				
			}
		logger.info("【基地天气更新】--【结束】----");
		} catch (Exception e) {
			logger.info("【基地天气更新】--【异常】----" + Exceptions.getStackTraceAsString(e));
		}
		
	}
	/**
	 * 解析天气字符串
	 * @param res 天气接口返回字符串
	 * @return WeatherParams
	 */
	public WeatherParams parseWeather(String res) {
		logger.info("解析天气情况---【开始】---" + res);
		WeatherParams wp = null;
		try {
			if (StringUtils.isNotEmpty(res)) {
				JSONObject jp = JSON.parseObject(res);
				JSONArray jList = jp.getJSONArray("HeWeather6");
				for (int i = 0; i < jList.size(); i++) {
					JSONObject obj = jList.getJSONObject(i);
					if ("ok".equals(obj.getString("status"))) {
						JSONObject nowJson = obj.getJSONObject("now");
						if (nowJson != null) {
							wp = new WeatherParams();
							String code = nowJson.getString("cond_code");
							if (Integer.parseInt(code) == 100) {
								wp.setCode("00"); //晴
								wp.setWeather(nowJson.getString("cond_txt"));
							} else if ((Integer.parseInt(code) >= 101 && Integer.parseInt(code) <= 104) || Integer.parseInt(code) >= 500) {
								wp.setCode("01"); //阴
								wp.setWeather(nowJson.getString("cond_txt"));
							} else if (Integer.parseInt(code) >= 300 && Integer.parseInt(code) <= 313) {
								wp.setCode("02"); //雨
								wp.setWeather(nowJson.getString("cond_txt"));
							} else if (Integer.parseInt(code) >= 200 && Integer.parseInt(code) <= 213) {
								wp.setCode("03"); //风
								wp.setWeather(nowJson.getString("cond_txt"));
							} else {
								wp.setCode("01");
								wp.setWeather(nowJson.getString("cond_txt"));
							}
							wp.setTemperature(nowJson.getString("tmp"));
							wp.setHumidity(nowJson.getString("hum"));
						}
					} else {
						logger.info("解析天气情况---【天气状态异常】---status=" + obj.getString("status"));
						return wp;
					}
				}
				return wp;
			} else {
				return wp;
			}
		} catch (Exception e) {
			logger.error("解析天气情况---【异常】---" + Exceptions.getStackTraceAsString(e));
			return wp;
		} finally {
			logger.info("解析天气情况---【结束】---");
		}
	}
	
	/**
	 * 根据城市获取天气
	 * @param baseName baseName
	 * @return String
	 */
	public String getWeather(String baseName) {
		String url = "https://free-api.heweather.com/s6/weather/now";
		String param = "key=30accb2e674c441d8ad8700e649157ee&location=" + baseName + "&lang=zh&unit=m";
		String res = null;
		try {
			res = WeatherUtil.weatherPost(url, param);
			logger.info("获取城市：" + baseName + "天气情况：[" + res + "]");
			return res;
		} catch (Exception e) {
			logger.info("获取城市：" + baseName + "天气----【异常】：" + Exceptions.getStackTraceAsString(e));
			return res;
		}
	}
}
